package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ciko.code.bean.UserBean;
import com.mywork.WorkUIKit;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.dialog.AccountLockedDialog;
import com.shwread.android.ui.dialog.BookTicketActivateDialog;
import com.shwread.android.ui.dialog.BookTicketTimeoutDialog;
import com.shwread.android.ui.dialog.GuideDialog;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.dialog.SimpleListener;
import com.shwread.android.ui.dialog.TicketDialogListener;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.face.ActivateEcardAction;
import com.shwread.httpsdk.http.face.UserLoginAction;
import com.shwread.httpsdk.util.Base64;
import com.shwread.httpsdk.util.DESUtil;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.util.List;

import logic.bean.LoginInfo;
import logic.beanenum.Ecard_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.NetworkUtil;
import logic.util.PopupWindowUtil;
import logic.util.TaiBaoLogin;
import logic.util.Util;


public class LoginAfterBookTicketActivateActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	public String                currCard, currCardPwd, account/* ,pwd */;
	private Context              context;
	private EditText             etPwd;
	private AutoCompleteTextView tvAccount;
	private TextView             tvTitle/* ,tvText,tvPwdText */;
	private Button               btnTitleBack, btnEnsure;
	private ImageView            ivAccountClear, ivClearPwd, ivShowPwd, ivAccountMore;
	//	public int resultCode;
	//	public String message;
	private int                  fromType;
	private PopupWindow          moreAccountPup;
	private List<UserBean>       users;
	private View                 vAccount, vAccountTxt;
	/** 密码是否可见 */
	private boolean              showPwd = false;
	@SuppressLint ("HandlerLeak")
	private Handler handler = new Handler()
	                        {
		                        @Override
		                        public void handleMessage(Message msg) {
			                        switch (msg.what) {
									}
								}
	                        };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_after_book_ticket_activate);
		context = this;
		Bundle bundle = getIntent().getExtras();
		//		if(bundle.containsKey(DefaultConsts.RESULT_CODE) && bundle.containsKey(DefaultConsts.RESULT_MESSAGE) &&  bundle.containsKey(DefaultConsts.CURR_ACCOUNT)){
		//			resultCode = bundle.getInt(DefaultConsts.RESULT_CODE);
		//			message = bundle.getString(DefaultConsts.RESULT_MESSAGE);
		//			currAccount = bundle.getString(DefaultConsts.CURR_ACCOUNT);
		//		}else{
		//			finish();
		//			return;
		//		}
		if (bundle.containsKey(DefaultConsts.CURR_CARD) && bundle.containsKey(DefaultConsts.CURR_PASSWORD) && bundle.containsKey(DefaultConsts.FROM_TYPE))
		{
			currCard = DESUtil.decrypt(bundle.getString(DefaultConsts.CURR_CARD));
			currCardPwd = DESUtil.decrypt(bundle.getString(DefaultConsts.CURR_PASSWORD));
			fromType = bundle.getInt(DefaultConsts.FROM_TYPE);
		}
		else
		{
			finish();
			return;
		}

		findView();
		addClick();
		initData();
		showHelp();
	}
	
	private void initData() {
		users = UserDao.getInstance(this).getAllUser();
		final UserBean user = UserDao.getInstance(this).getLastLoginUser();
		if (DefaultConsts.TAG_LOGIN != fromType)
		{
			ivAccountMore.setVisibility(View.GONE);
			tvAccount.setText(Const.phone_number);
		}
		if (DefaultConsts.TAG_LOGIN == fromType && user != null)
		{
			ivAccountMore.setVisibility(View.VISIBLE);
			tvAccount.setText(user.getAccount());
		}

		//		tvPwdText.setText(resultCode==DefaultConsts.OLD_USER_CODE ? "密码" : "设置密码");
		//		etPwd.setHint(resultCode==DefaultConsts.OLD_USER_CODE ? "请输入密码" : "新密码");
		//		if(resultCode==DefaultConsts.NEW_USER_CODE){
		//			tvAccount.setEnabled(false);
		//			ivAccountClear.setVisibility(View.GONE);
		//		}

	}
	
	private void findView() {
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		btnTitleBack = (Button) findViewById(R.id.common_header_back);
		//		tvText = (TextView) findViewById(R.id.login_after_book_ticket_activate_text_tv);
		//		tvPwdText = (TextView) findViewById(R.id.login_after_book_ticket_activat_pwd_tv);
		tvAccount = (AutoCompleteTextView) findViewById(R.id.login_after_book_ticket_activat_account_et);
		etPwd = (EditText) findViewById(R.id.login_after_book_ticket_activat_pwd_et);
		ivAccountClear = (ImageView) findViewById(R.id.login_after_book_ticket_activat_account_clear_iv);
		ivAccountMore = (ImageView) findViewById(R.id.login_after_book_ticket_activat_account_more_iv);
		ivClearPwd = (ImageView) findViewById(R.id.login_after_book_ticket_activat_pwd_clear_iv);
		ivShowPwd = (ImageView) findViewById(R.id.login_after_book_ticket_activat_pwd_show_iv);
		btnEnsure = (Button) findViewById(R.id.login_after_book_ticket_activate_ensure_btn);
		vAccount = findViewById(R.id.book_ticket_activate_account_ll);
		vAccountTxt = findViewById(R.id.login_after_book_ticket_activat_account_txt);

		tvTitle.setText("绑定帐号");
		//		tvText.setText(Util.isEmpty(message)?"":message);
		btnTitleBack.setVisibility(View.VISIBLE);

		//		final String str = getResources().getString(DefaultConsts.TAG_LOGIN == fromType ? R.string.login_activation_text : R.string.setting_activation_text);
		//		((TextView)findViewById(R.id.login_after_book_ticket_activat_bottom_txt)).setText(str);
		if (DefaultConsts.TAG_LOGIN == fromType)
		{
			final String str = getResources().getString(R.string.login_activation_text);
			((TextView) findViewById(R.id.login_after_book_ticket_activat_bottom_txt)).setText(str);
		}
		else
		{
			findViewById(R.id.login_after_book_ticket_activat_bottom_txt).setVisibility(View.GONE);
		}

		//		findViewById(R.id.login_after_book_ticket_activat_pwd_layout).setVisibility(View.GONE);
		//		findViewById(R.id.login_after_book_ticket_activat_pwd_txt).setVisibility(View.GONE);

	}
	
	private void addClick() {
		btnTitleBack.setOnClickListener(this);
		btnEnsure.setOnClickListener(this);
		ivClearPwd.setOnClickListener(this);
		ivShowPwd.setOnClickListener(this);
		etPwd.addTextChangedListener(new TextChangedListener(ivClearPwd, ivShowPwd));
		etPwd.setOnFocusChangeListener(new FocusChangeListener(etPwd, ivClearPwd));
		//		if(resultCode != DefaultConsts.NEW_USER_CODE){
		ivAccountClear.setOnClickListener(this);
		ivAccountMore.setOnClickListener(this);
		tvAccount.addTextChangedListener(new TextChangedListener(ivAccountClear));
		tvAccount.setOnFocusChangeListener(new FocusChangeListener(tvAccount, ivAccountClear));
		//		}
	}
	
	private void clickLogin() {
		if (!NetworkUtil.isNetAvailable(this))
		{
			new NetworkDialog(this).show();
			return;
		}
		account = tvAccount.getText().toString().trim();
		//		pwd = etPwd.getText().toString().trim();

		if (Util.isEmpty(account))
		{
			Util.showToast(this, "请输入帐号");
		}
		else if (!Util.isMobile(account))
		{
			Util.showToast(this, "建议输入手机号享受更多服务哦");
		}
		//		else if (DefaultConsts.TAG_LOGIN==fromType && Util.isEmpty(pwd))
		//		{
		//			if(resultCode==DefaultConsts.NEW_USER_CODE){
		//				Util.showToast(this, "请设置登录密码");
		//			}else{
		//				Util.showToast(this, "请输入密码");
		//			}
		//		}
		//		else if ((DefaultConsts.TAG_LOGIN==fromType && (pwd.length()<6 || pwd.length()>16))||!Util.isStringValid(etPwd.getText().toString()))
		//		{
		//			Util.showToast(this, "密码是6-16位哦");
		//		}
		else
		{
			//TODO  调用激活接口，成功后再掉登录

			if (DefaultConsts.TAG_LOGIN == fromType)
			{
				new ActivateEcardAction(this, account, currCard, currCardPwd, Ecard_Enum.ACTIVATE.getValue(), "0", "", currCardPwd, new MActionListener()).start();
				//				new ActivateEcardAction(this, account, currCard, currCardPwd, Ecard_Enum.ACTIVATE.getValue(), "0", "",pwd, new MActionListener()).start();
			}
			else
			{
				if (Const.phone_number.equals(account))
				{
					new ActivateEcardAction(this, account, currCard, currCardPwd, Ecard_Enum.ACTIVATE.getValue(), "1", "", "", new MActionListener()).start();
				}
				else
				{
					new ActivateEcardAction(this, Const.phone_number, currCard, currCardPwd, Ecard_Enum.GIVE.getValue(), "1", account, "", new MActionListener()).start();
				}

			}

			//			if(resultCode==DefaultConsts.OLD_USER_CODE){ //老用户调用登录接口
			//				new UserLoginAction(this, account, pwd, new LoginListener()).start();
			//			}else if(resultCode==DefaultConsts.NEW_USER_CODE){ //新用户调用登录并设置新密码接口
			//				new UserLoginAndSetPwdAction(this, account, pwd, new LoginListener()).start();
			//			}
		}
	}
	
	private void showDialog(boolean isSuccess, String message) {
		new BookTicketActivateDialog(this, isSuccess, message, new DialogListener()).show();
	}
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (fromType == DefaultConsts.TAG_LOGIN)
			{
				startActivity(new Intent(this, NewLoginActivity.class));
			}
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				if (fromType == DefaultConsts.TAG_LOGIN)
				{
					startActivity(new Intent(this, NewLoginActivity.class));
				}
				finish();
				break;
			case R.id.login_after_book_ticket_activate_ensure_btn:
				clickLogin();
				break;
			case R.id.login_after_book_ticket_activat_pwd_clear_iv:
				etPwd.setText("");
				ivClearPwd.setVisibility(View.GONE);
				break;
			case R.id.login_after_book_ticket_activat_pwd_show_iv:
				//TODO
				showPwd = !showPwd;
				if (showPwd)
				{
					ivShowPwd.setImageResource(R.drawable.pwd_on);
					etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				}
				else
				{
					ivShowPwd.setImageResource(R.drawable.pwd_off);
					etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				}
				Editable etable = etPwd.getText();
				Selection.setSelection(etable, etable.length());
				break;
			case R.id.login_after_book_ticket_activat_account_clear_iv:
				tvAccount.setText("");
				ivAccountClear.setVisibility(View.GONE);
				break;
			case R.id.login_after_book_ticket_activat_account_more_iv:
				initDropPop();
				break;
		}
	}
	
	@SuppressLint ("InlinedApi")
	@SuppressWarnings ("deprecation")
	void initDropPop() {
		Util.hideInputMethodManager(context, tvAccount);
		final View view = new PopupWindowUtil(this, users, new ItemClick()).getView();
		final int width = vAccount.getWidth() - vAccountTxt.getWidth();
		moreAccountPup = new PopupWindow(view, width, LayoutParams.WRAP_CONTENT);
		moreAccountPup.setBackgroundDrawable(new BitmapDrawable());
		moreAccountPup.setFocusable(true);
		moreAccountPup.showAsDropDown(tvAccount, 0, 0);
	}
	
	void toMainActivity() {
		Intent intent = new Intent(this, MainActivity.class);
		intent.setAction(MainActivity.TO_ENTERPRISE_ACTION);
		startActivity(intent);
		finish();
	}
	
	private void showHelp() {
		QyreaderPerferencesUtil xmlUtil = QyreaderPerferencesUtil.getInstance(this, DefaultConsts.FIRST_TAG);
		//		xmlUtil.setFirstEcardLogin(true);//测试
		if (xmlUtil.isFirstEcardLogin() && DefaultConsts.TAG_LOGIN != fromType)
		{
			//			LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
			//			View view = inflater.inflate(R.layout.ecard_login_firstin, null);
			//			final Dialog dialog = new Dialog(this,R.style.ecard_login_dialog);
			//			dialog.setContentView(view);
			//			Button closeBtn = (Button) view.findViewById(R.id.ecard_login_firstin_btn);
			//			closeBtn.setOnClickListener(new OnClickListener()
			//			{
			//				@Override
			//				public void onClick(View v)
			//				{
			//					dialog.dismiss();
			//				}
			//			});
			//			dialog.show();
			new GuideDialog(this, R.layout.ecard_login_firstin).show();
			xmlUtil.setFirstEcardLogin(false);
		}
	}
	
	class MActionListener
	        implements
	        ActionListener
	{

		@Override
		public void OK(final Object obj) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					showDialog(true, obj.toString());
				}
			});
		}

		@Override
		public void ERROR(final int code, final String msg) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					if (code == 2100)
					{//电子券信息错误,这个也需要显示dialog,待测试
						showDialog(false, msg);
					}
					else
					{
						Util.showToast(LoginAfterBookTicketActivateActivity.this, msg);
					}
				}
			});
		}

		@Override
		public void HTTPERROR(int statusCode) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					Util.showToast(LoginAfterBookTicketActivateActivity.this, "请求超时，请重试！");
				}
			});
		}
	}
	
	private class DialogListener
	        implements
	        SimpleListener
	{
		@Override
		public void ok() {
			if (DefaultConsts.TAG_LOGIN == fromType)
			{
				new UserLoginAction(LoginAfterBookTicketActivateActivity.this, account, currCardPwd, new LoginListener()).start();
				//				new UserLoginAction(LoginAfterBookTicketActivateActivity.this, account, pwd, new LoginListener()).start();
				//登录太保平台
				new TaiBaoLogin().taibaoLogin(context, account);
			}
			else
			{
				finish();
			}
		}
	}
	
	private class LoginListener
	        implements
	        ActionListener
	{
		@Override
		public void OK(Object obj) {
			final LoginInfo info = (LoginInfo) obj;
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					UserBean user = UserDao.getInstance(context).getUser(account);
					long loginTime = System.currentTimeMillis();
					if (null == user)
					{
						user = new UserBean(account, Base64.encode(currCardPwd, "utf-8"), info.getKey(), loginTime, 1, info.getAccId(), info.getToken(), info.getStaffId());
					}
					else
					{
						user.setPassword(Base64.encode(currCardPwd, "utf-8"));
						user.setLoginTime(loginTime);
						user.setKey(info.getKey());
						user.setStaffId(info.getStaffId());
						user.setIsKeepPwd(1);
					}
					WorkUIKit.setAccount(user.getAccount());
					WorkUIKit.setUserId(user.getStaffId());

					UserDao.getInstance(context).addUser(user);
					Const.isActivationError = false;
					toMainActivity();
				}
			});
		}

		@Override
		public void ERROR(final int resultCode, String message) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					if (resultCode == DefaultConsts.TIMEOUT_CODE)
					{
						//TODO 新用户登陆，设置密码有效期超时
						new BookTicketTimeoutDialog(context, new MyListener()).show();
					}
					else if (resultCode == ResultCode.E_9997)
					{
						AccountLockedDialog accountLockedDialog = new AccountLockedDialog(context);
						accountLockedDialog.show();
					}
					else
					{
						Util.showToast(context, "密码错误");
					}
				}
			});
		}

		@Override
		public void HTTPERROR(int statusCode) {
		}
	}
	
	private class MyListener
	        implements
	        TicketDialogListener
	{
		@Override
		public void getPwd() {
			Intent forgetPwdIntent = new Intent(LoginAfterBookTicketActivateActivity.this, ForgetPwdActivity.class);
			forgetPwdIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(forgetPwdIntent);
			finish();
		}

		@Override
		public void login() {
			startActivity(new Intent(LoginAfterBookTicketActivateActivity.this, NewLoginActivity.class));
			finish();
		}
	}
	
	private class ItemClick
	        implements
	        OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			tvAccount.setText(users.get(arg2).getAccount());
			moreAccountPup.dismiss();
		}
	}
	
	private class TextChangedListener
	        implements
	        TextWatcher
	{
		View[] views;

		public TextChangedListener(View... views) {
			this.views = views;
		}

		@Override
		public void afterTextChanged(Editable arg0) {
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		}

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			for (int i = 0; i < views.length; i++)
			{
				views[i].setVisibility(Util.isEmpty(s.toString()) ? View.GONE : View.VISIBLE);
			}
		}
	}
	
	private class FocusChangeListener
	        implements
	        OnFocusChangeListener
	{
		View     view;
		EditText et;

		public FocusChangeListener(EditText et, View view) {
			this.view = view;
			this.et = et;
		}

		@Override
		public void onFocusChange(View arg0, boolean arg1) {
			boolean value = arg1 && Util.isNotEmpty(et.getText().toString().trim());
			view.setVisibility(value ? View.VISIBLE : View.GONE);
		}
	}
	
}
